import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/route_manager.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:zootix/zt_config.dart';
import 'package:zootix/constants/zt_router.dart';
import 'package:zootix/services/zt_storage.service.dart';
import 'package:zootix/store/zt_auth.store.dart';
import 'package:zootix/zt_app_theme.dart';
import 'package:zootix/util/zt_loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zootix/widgets/zt_refresh-footer.dart';
import 'package:zootix/widgets/zt_refresh_header.dart';

import 'constants/zt_constants.dart';
import 'services/zt_app_info.service.dart';

// The index screen shows login if no user identity was found, otherwise the landing screen
class ZtIndex extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
        minTextAdapt: true,
        designSize: Size(375, 812),
        builder: () => RefreshConfiguration(
            headerBuilder: () => ZtRefreshHeader(),
            footerBuilder: () => ZtRefreshFooter(),
            hideFooterWhenNotFull: true,
            headerTriggerDistance: 30,
            maxOverScrollExtent: 80,
            footerTriggerDistance: 150,
            child: GetMaterialApp(
                theme: theme,
                title: ZtGloablConfig.DOMAIN_NAME,
                getPages: ZtRouteConfig.getPages,
                initialRoute: getInitialRoute(),
                // initialRoute: ZtRouteConfig.onboarding,
                debugShowCheckedModeBanner: false,
                builder: EasyLoading.init(builder: (context, widget) {
                  //必须render的时候注册
                  ScreenUtil.setContext(context);
                  ZtLoadingUtil().init();
                  return Obx(() => MediaQuery(
                      //设置文字大小不随系统设置改变
                      data: MediaQuery.of(context).copyWith(
                          textScaleFactor: ZtAppInfoService.to.scale.value),
                      child: GestureDetector(
                        onTap: () {
                          FocusScopeNode currentFocus = FocusScope.of(context);
                          if (!currentFocus.hasPrimaryFocus &&
                              currentFocus.focusedChild != null) {
                            FocusManager.instance.primaryFocus?.unfocus();
                          }
                        },
                        child: widget!,
                      )));
                }))));
  }

  String getInitialRoute() {
    if (ZtAppInfoService.to.checkIsFirstInstall()) {
      return ZtRouteConfig.onboarding;
    }
    return ZtStorageService.to
                .getString(ZtCacheKeys.token, isWithUser: false) ==
            null
        ? ZtRouteConfig.login
        : ZtRouteConfig.home;
  }
}
